
"""
"""

from weakref import ref

class UnknownEventException(Exception):
    pass

class EventManagerClass(object):
    callbacks = {}
    instance = None
    def __new__(cls):
        if cls.instance == None:
            self = super(eventManager, cls).__new__(cls)
            cls.instance = self
            self.callbacks = {}
        else:
            self = cls.instance
        return self
    
    def registerEvent(self, name):
        if not name in self.callbacks:
            self.callbacks[name] = []
    
    def triggerEvent(self, name, *pargs, **kwargs):
        for f in self.callbacks[name]:
            try:
                f(*pargs, **kwargs)
            except:
                import traceback
                traceback.print_exc()
    
    def registerCallback(self, name, function):
        if name not in self.callbacks.keys():
            raise UnknownEventException, "Event not registered"
        self.callbacks[name].append(ref(function))
        return True
    
    def unregisterCallback(self, name, function):
        if name not in self.callbacks.keys():
            raise UnknownEventException, "Event not registered"
        if function not in self.callbacks[name]:
            return True
        cbs = self.callbacks[name]
        for r in weakref.getweakrefs(function):
            if r in cbs:
                cbs.remove(r)

EventManager = EventManager()